package edu.bbk.muc.lifetracker;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import edu.bbk.muc.lifetracker.common.Configuration;
import edu.bbk.muc.lifetracker.common.Event;
import edu.bbk.muc.lifetracker.logging.FileStorer;
import edu.bbk.muc.lifetracker.logging.LocationToolTipKMLLogger;
import edu.bbk.muc.lifetracker.logging.Logger;
import edu.bbk.muc.lifetracker.logging.TextLogger;
import edu.bbk.muc.lifetracker.sensormanager.PhysicalSensorFactory;
import edu.bbk.muc.lifetracker.sensormanager.SensorManager;

/**
 * Main application activity
 * @author irenatyler and romankirillov
 */
public class LifeTracker extends Activity {
  private TextView eventsCollected;
  private TextView refreshRate;
  private SensorManager sensorManager = null;
  private DbAdapter dbAdapter;

  private TextView status;
  private SharedPreferences preferences;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_screen);
    status = (TextView) findViewById(R.id.current_status_label);
    refreshRate = (TextView) findViewById(R.id.refresh_rate_label);
    eventsCollected = (TextView) findViewById(R.id.events_collected_label);

    Resources res = getResources();

    status.setText(String.format(res.getString(R.string.current_status), "Unknown"));
    refreshRate.setText(String.format(res.getString(R.string.refresh_rate), "Not Refreshed"));
    eventsCollected.setText(String.format(res.getString(R.string.events_collected), 0));

    Configuration initialConfig = applyPreferences();
    dbAdapter = new DbAdapter(this);
    dbAdapter.open();
    dbAdapter.getEventReceiver().addChainedEventReceiver(new EventReceiver() {

      @Override
      public void addChainedEventReceiver(EventReceiver next) {
      }

      @Override
      public void onEventReady(Event event) {
        LifeTracker.this.eventsCollected.setText("Events collected: " + dbAdapter.getNumEvents());
      }
    });

    sensorManager =
        new SensorManager(initialConfig, new SensorCallbackReceiver(initialConfig,
            dbAdapter.getEventReceiver()), this, new PhysicalSensorFactory());
    applyPreferences();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);

    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.options_menu_item: {
      Intent settings = new Intent(this, Preferences.class);
      startActivityForResult(settings, 987);
      break;
    }
    case R.id.clear_log_menu_item: {
      new AlertDialog.Builder(LifeTracker.this)
            .setMessage("Do you want to delete all log entries").setTitle("Are you sure?")
            .setPositiveButton("Yes", new OnClickListener() {
              @Override
              public void onClick(DialogInterface arg0, int arg1) {
                dbAdapter.clearAllEvents();
                new AlertDialog.Builder(LifeTracker.this).setMessage("All events were removed")
                    .setTitle("Done").show();
              }
            }).setNegativeButton("No", null).show();
      break;
    }
    case R.id.debug_menu: {

      Logger logger;
      boolean outputToKml = preferences.getString("output_format_list", "KML").equals("KML");

      if (!outputToKml) {
        logger = new TextLogger(this.dbAdapter);
      } else {
        // default behaviour
        logger = new LocationToolTipKMLLogger(this.dbAdapter);
      }
      new AlertDialog.Builder(LifeTracker.this).setMessage(logger.getType())
          .setTitle("Done").show();
      FileStorer fileStorer = new FileStorer(logger);
      if (fileStorer.storeFile()) {
        new AlertDialog.Builder(LifeTracker.this)
            .setMessage(logger.getType() + " was written to " +
                fileStorer.getFile().getAbsolutePath()).setTitle("Done").show();
      }
      break;
    }
    case R.id.help_menu: {
      new AlertDialog.Builder(LifeTracker.this)
            .setMessage("Irena Tyler & Roman Kirillov").setTitle("MUC coursework").show();
      break;
    }
    }

    return true;
  }

  /**
   * Is called whenever initial configuration received or preferences window is
   * closed (hence configuration may have changed).
   */
  private Configuration applyPreferences() {
    Log.d("LifeTracker", "applyPreferences Called");
    this.preferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean loggingEnabled = preferences.getBoolean("logging_enabled", true);
    Configuration config =
        new Configuration.SimpleConfiguration(loggingEnabled, preferences.getBoolean(
            "acceleration_enabled", true) && loggingEnabled, preferences.getBoolean(
            "ambient_light_enabled", true) && loggingEnabled, true && loggingEnabled);

    if (null != sensorManager) {
      sensorManager.onConfigurationChanged(config);
    }

    this.status.setText(loggingEnabled ? "Logging is active" : "Logging is inactive");
    this.refreshRate.setText("");

    return config;
  }

  private void stopAll() {
    Configuration allDisabled = new Configuration.SimpleConfiguration(false, false, false, false);
    if (null != sensorManager) {
      sensorManager.onConfigurationChanged(allDisabled);
    }
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 987) {
      applyPreferences();
    }

    super.onActivityResult(requestCode, resultCode, data);
  }

  @Override
  protected void onDestroy() {
    stopAll();
    super.onDestroy();
  }

  @Override
  protected void onPause() {
    stopAll();
    super.onPause();
  }

  @Override
  protected void onRestart() {
    applyPreferences();
    super.onRestart();
  }

  @Override
  protected void onResume() {
    applyPreferences();
    super.onResume();
  }

  @Override
  protected void onStop() {
    stopAll();
    super.onStop();
  }
}
